<template>
  <div>
    <div v-if="dataList.length == 0">
      <div class="chart-title">
        {{ $t('deviceDetail.userTrend', [timeRange.chartTitle]) }}
      </div>
      <a-empty :image="simpleImage" />
    </div>
    <chart
      :options="userOptions"
      :style="{ height: height + 'px' }"
      :title="userTitle"
      v-else
    />
    <div v-if="dataList.length == 0">
      <div class="chart-title">
        {{ $t('deviceDetail.painTrend', [timeRange.chartTitle]) }}
      </div>
      <a-empty :image="simpleImage" />
    </div>
    <chart
      :options="sessOptions"
      :style="{ height: height + 'px', marginTop: '20px' }"
      :title="sessTitle"
      v-else
    />
  </div>
</template>

<script>
import { Empty } from 'ant-design-vue';
import { requestHttp, maccApi, fillTimeLineData } from '@utils/index';
import chart from './publicChart.vue';
import moment from 'moment-timezone';
export default {
  data() {
    return {
      userOptions: {},
      sessOptions: {},
      userTitle: '',
      sessTitle: '',
      dataList: [],
      simpleImage: Empty.PRESENTED_IMAGE_SIMPLE,
    };
  },
  props: {
    deviceInfo: {
      type: Object,
      default: () => {},
    },
    timeRange: {
      type: Object,
      default: () => {
        return {
          end: +new Date(),
          start: +new Date() - 48 * 3600 * 1000,
        };
      },
    },
    height: {
      type: Number,
      default: 250,
    },
  },
  components: {
    chart,
  },
  computed: {
    timezone() {
      const currentGroup = this.$store.state.Group.groupMap[
        this.deviceInfo.groupId
      ];
      return (currentGroup && currentGroup.timezone) || '';
    },
  },
  watch: {
    timeRange: {
      handler() {
        this.getUsersessiontrend();
      },
      deep: true,
    },
    deviceInfo: {
      handler() {
        this.getUsersessiontrend();
      },
      deep: true,
    },
  },
  beforeCreate() {
    this.simpleImage = Empty.PRESENTED_IMAGE_SIMPLE;
  },
  mounted() {
    this.getUsersessiontrend();
  },

  methods: {
    //egw用户数，会话趋势图
    async getUsersessiontrend() {
      if (!this.timeRange) {
        return;
      }
      const { start, end } = this.timeRange;
      this.userTitle = this.getChartTitle('user');
      this.sessTitle = this.getChartTitle('session');
      const productType =
        ['EGW', 'EWR'].indexOf(this.deviceInfo.productType) > -1 ? 'egw' : 'eg';
      const res = await requestHttp({
        api: `${maccApi.GET_USERSESSION_TREND.replace(
          '{productType}',
          productType
        )}?sn=${
          this.deviceInfo.serialNumber
        }&type=day&start=${start}&end=${end}`,
        method: 'GET',
        module: 'logbiz',
      });
      if (res.code != 0) {
        this.$message.error(res.msg || this.$t('deviceDetail.egwFail'));
        return;
      }
      this.dataList = res.data || [];
      if (res.data && res.data.length > 0) {
        let gatherTimeList = [];
        let userCountList = [];
        let sessionCountList = [];
        let data = res.data;
        const list = fillTimeLineData(data, start, end, 'gatherTime', 300, 900);
        for (const key in list) {
          gatherTimeList.push(
            moment(list[key].gatherTime)
              .tz(this.timezone)
              .format('YYYY/MM/DD HH:mm:ss')
          );

          if (
            list[key].userCount != undefined ||
            list[key].userNumber != undefined
          ) {
            if (list[key].userCount != undefined) {
              userCountList.push(list[key].userCount);
            } else {
              userCountList.push(list[key].userNumber);
            }
          } else {
            userCountList.push('-');
          }
          if (
            list[key].sessionCount != undefined ||
            list[key].session != undefined
          ) {
            if (list[key].sessionCount != undefined) {
              sessionCountList.push(list[key].sessionCount);
            } else {
              sessionCountList.push(list[key].session);
            }
          } else {
            sessionCountList.push('-');
          }
        }
        this.userOptions = this.getLineChartOptions({
          timeList: gatherTimeList,
          dataList: userCountList,
          name: this.$t('deviceDetail.users'),
          title: this.userTitle,
        });
        this.sessOptions = this.getLineChartOptions({
          timeList: gatherTimeList,
          dataList: sessionCountList,
          name: this.$t('deviceDetail.sessions'),
          title: this.sessTitle,
        });
      } else {
        this.userOptions = {};
        this.sessOptions = {};
      }
    },
    getChartTitle(chartType) {
      const { chartTitle = '' } = this.timeRange;
      return `${chartTitle} ${
        chartType == 'user'
          ? this.$t('deviceDetail.clientchart')
          : this.$t('deviceDetail.sessionchart')
      }`;
    },

    getLineChartOptions(data) {
      //console.log('data.timeList', data.timeList);
      const self = this;
      const { chartTitle = '' } = self.timeRange;
      let label;
      let option = {
        title: {
          text: data.title,
          textStyle: {
            fontSize: 14,
            fontStyle: 'normal',
            fontWeight: 'bolder',
          },
        },
        color:
          data.name == self.$t('deviceDetail.users') ? '#74DEED' : '#9EB0FE',
        grid: {
          left: '5%',
          right: '5%',
          bottom: '10%',
        },
        tooltip: {
          trigger: 'axis',
          textStyle: {
            align: 'left',
            color: 'rgba(255,255,255,1)',
          },
          backgroundColor: 'rgba(0,0,0,0.5)', //设置背景图片 rgba格式
          borderWidth: 0,
          padding: 5,
          formatter: function (params) {
            let res = '';
            let restop = '';
            for (let i = 0; i < params.length; i++) {
              restop = '<span>' + params[i].axisValue + '</span><br/>';
              res +=
                '<span>' +
                params[i].marker +
                params[i].seriesName +
                ' : ' +
                params[i].data +
                '</span><br/>';
            }
            return restop + res;
          },
          axisPointer: {
            type: 'cross',
            animation: false,
            label: {
              backgroundColor: '#505765',
            },
          },
        },
        xAxis: {
          name: self.$t('deviceDetail.hour'),
          type: 'category',
          boundaryGap: false,
          axisLine: {
            onZero: false,
          },
          axisTick: {
            show: false,
          },
          axisLabel: {
            formatter: function formatter(value, index) {
              if (chartTitle == self.$t('deviceDetail.lastOneHour')) {
                return moment(value).format('HH:mm');
              } else {
                return moment(value).format('H');
              }
            },
            interval: function interval(index, value) {
              if (chartTitle == self.$t('deviceDetail.lastOneHour')) {
                return true;
              }
              const string = moment(value).format('H');
              if (label != string && parseInt(string) % 2 == 0) {
                label = string;
                return true;
              } else {
                return false;
              }
            },
          },
          data: data.timeList,
        },
        yAxis: [
          {
            name: `${data.name}${self.$t('deviceDetail.ge')}`,
            type: 'value',
            axisLine: {
              show: false,
            },
            axisTick: {
              show: false,
            },
          },
        ],
        series: [
          {
            name: data.name,
            type: 'line',
            smooth: true,
            areaStyle: {},
            lineStyle: {
              width: 1,
            },
            data: data.dataList,
          },
        ],
      };
      return option;
    },
  },
};
</script>

<style lang="less" scoped>
.chart-title {
  font-size: 14px;
  font-weight: bolder;
}
</style>
